package me.shurufa.widget.popupwindow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.kaopiz.kprogresshud.KProgressHUD;

import net.qiujuer.genius.blur.StackBlur;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import me.shurufa.R;
import me.shurufa.share.ScreenShot;
import me.shurufa.share.ShareContentPic;
import me.shurufa.share.ShareController;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.SinaShareManager;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/24 09:23
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 分享Popupwindow
 */
public class SharePopupWindow extends PopupWindow implements View.OnClickListener {

    private LinearLayout mGalleryBtn;
    private LinearLayout mWeixinBtn;
    private LinearLayout mWeixinCircleBtn;
    private LinearLayout mWeiboBtn;
    private LinearLayout mQQBtn;
    private LinearLayout mQzoneBtn;

    private View rootView;
    private Activity mContext;
    private View popRoot;
    //  blur
    private int mWidth;
    private int mHeight;
    private int statusBarHeight;
    private Bitmap mBitmap = null;
    private Bitmap overlay = null;
    private Animation mShowAnim;

    private String mShareImagePath;
    private LinearLayout mShareView;

    public SharePopupWindow(Context context) {
        super(context);
        mContext = (Activity) context;
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setOutsideTouchable(true);
        mShowAnim = AnimationUtils.loadAnimation(context, R.anim.popup_iut_anim_alpha);
        mShowAnim.setAnimationListener(new ShowAnimationListener());
        LayoutInflater mLayoutInflater = LayoutInflater.from(context);
        rootView = mLayoutInflater.inflate(R.layout.popup_share, null);
        popRoot = rootView.findViewById(R.id.root);

        setContentView(rootView);
        initView();

    }

    /**
     * 初始化控件
     */
    private void initView() {

        mGalleryBtn = (LinearLayout) rootView.findViewById(R.id.btn_gallery);
        mWeixinBtn = (LinearLayout) rootView.findViewById(R.id.btn_weixin);
        mWeixinCircleBtn = (LinearLayout) rootView.findViewById(R.id.btn_weixin_circle);
        mWeiboBtn = (LinearLayout) rootView.findViewById(R.id.btn_weibo);
        mQQBtn = (LinearLayout) rootView.findViewById(R.id.btn_qq);
        mQzoneBtn = (LinearLayout) rootView.findViewById(R.id.btn_qzone);

        mGalleryBtn.setOnClickListener(this);
        mWeixinBtn.setOnClickListener(this);
        mWeixinCircleBtn.setOnClickListener(this);
        mWeiboBtn.setOnClickListener(this);
        mQQBtn.setOnClickListener(this);
        mQzoneBtn.setOnClickListener(this);
        rootView.findViewById(R.id.iv_close).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        ShareController controller = new ShareController(mContext);
        switch (v.getId()) {
            case R.id.btn_gallery:
                savePicToGallery();
                break;
            case R.id.btn_weixin:
                shareToWechat(0);
                break;
            case R.id.btn_weixin_circle:
                shareToWechat(1);
                break;
            case R.id.btn_weibo:
                controller.shareToWeibo(mContext, mShareView);
                break;
            case R.id.btn_qq:
                controller.shareToQQ(mContext, mShareView);
                break;
            case R.id.btn_qzone:
                controller.shareToQZone(mContext, mShareView);
                break;
        }
        dismiss();
    }

    private void savePicToGallery() {

        if (kProgressHUD == null) {
            kProgressHUD = KProgressHUD.create(mContext);
        }
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在生成长图...")
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = ScreenShot.compressImage(ScreenShot.getBitmapByView(mShareView), 500);
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Bitmap bm = ScreenShot.compressImage(ScreenShot.getBitmapByView(mShareView));
                        String path = "";
                        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                            path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/roobook";
                        }

                        final File f = new File(path, System.currentTimeMillis()+ ".jpg");
                        if (f.exists()) {
                            f.delete();
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(f);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        mContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                Uri uri = Uri.fromFile(f);
                                intent.setData(uri);
                                mContext.sendBroadcast(intent);
                                Utils.showToast("保存成功");
                                if (kProgressHUD != null) {
                                    kProgressHUD.dismiss();
                                    kProgressHUD = null;
                                }
                            }
                        });
                    }
                });
            }
        }).start();

    }

    private KProgressHUD kProgressHUD;
    // 0 好友， 1 朋友圈
    private void shareToWechat(final int flag) {
        // 生成Bitmap

        if (kProgressHUD == null) {
            kProgressHUD = KProgressHUD.create(mContext);
        }
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在生成长图...")
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = ScreenShot.compressImage(ScreenShot.getBitmapByView(mShareView), 150);
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (kProgressHUD != null) {
                            kProgressHUD.dismiss();
                            kProgressHUD = null;
                        }

                        ShareController controller = new ShareController(mContext);
                        controller.shareToWeChat(flag, null, null, null, bitmap);
                    }
                });
            }
        }).start();
    }


/////////////////////////////////////////////////////

    /**
     * 实例化后需要手动调用改方法 用于截图做模糊处理
     */
    public void init() {
        Rect frame = new Rect();
        mContext.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;
        LogUtils.d("EditDigest", "" + statusBarHeight);
        DisplayMetrics metrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay()
                .getMetrics(metrics);
        mWidth = metrics.widthPixels;
        mHeight = metrics.heightPixels;

        setWidth(mWidth);
        setHeight(mHeight);
        mShowAnim.setFillAfter(true);
        mShowAnim.setDuration(500);
    }

    private Bitmap blur(int i) {
        long startMs = System.currentTimeMillis();
        // Is scale
        View view = mContext.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        mBitmap = view.getDrawingCache();
        //TODO 去掉通知栏
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        mBitmap = Bitmap.createBitmap(mBitmap, 0, statusBarHeight, width, height - statusBarHeight);
        height -= statusBarHeight;
        float scaleFactor = 8;//缩放比例
        float radius = 8;//模糊程度

        overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        //is blur
        // Java
        if (i == 1)
            overlay = StackBlur.blur(overlay, (int) radius, false);
            // Bitmap JNI Native
        else if (i == 2)
            overlay = StackBlur.blurNatively(overlay, (int) radius, false);
            // Pixels JNI Native
        else if (i == 3)
            overlay = StackBlur.blurNativelyPixels(overlay, (int) radius, false);

        LogUtils.d("EditDigestWindow", "blur time is:" + (System.currentTimeMillis() - startMs));
        return overlay;
    }

    public void show(View anchor, int bottomMargin, LinearLayout view) {

        mShareView = view;


        android.widget.RelativeLayout.LayoutParams params =
                new android.widget.RelativeLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,
                        AbsoluteLayout.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = bottomMargin;
        params.topMargin = 200;
        params.leftMargin = 18;
        popRoot.setAnimation(mShowAnim);
        //TODO 设置内部控件 Anim
        setAnimationStyle(android.R.style.Animation_Toast);
        //设置背景高斯模糊
        setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), blur(2)));
        //外部是否可以点击
        setOutsideTouchable(true);
        setFocusable(true);
        showAtLocation(anchor, Gravity.BOTTOM, 0, statusBarHeight);
        popRoot.startAnimation(mShowAnim);
    }

    public void show(View anchor, int bottomMargin, String shareImagePath) {

        mShareImagePath = shareImagePath;


        android.widget.RelativeLayout.LayoutParams params =
                new android.widget.RelativeLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,
                        AbsoluteLayout.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = bottomMargin;
        params.topMargin = 200;
        params.leftMargin = 18;
        popRoot.setAnimation(mShowAnim);
        //TODO 设置内部控件 Anim
        setAnimationStyle(android.R.style.Animation_Toast);
        //设置背景高斯模糊
        setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), blur(2)));
        //外部是否可以点击
        setOutsideTouchable(true);
        setFocusable(true);
        showAtLocation(anchor, Gravity.BOTTOM, 0, statusBarHeight);
        popRoot.startAnimation(mShowAnim);
    }

    @Override
    public void dismiss() {
        destroy();
        LogUtils.kLog().e("ShelvesWindow.dismiss()");
        super.dismiss();
    }

    public void destroy() {
        if (null != overlay) {
            overlay.recycle();
            overlay = null;
            System.gc();
        }
        if (null != mBitmap) {
            mBitmap.recycle();
            mBitmap = null;
            System.gc();
        }

    }

    private class ShowAnimationListener implements Animation.AnimationListener {
        public void onAnimationEnd(Animation animation) {
        }

        public void onAnimationRepeat(Animation animation) {

        }

        public void onAnimationStart(Animation animation) {

        }

    }
}
